package admin

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
)

// 获取捐助记录
func JuanzengList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MJuanZeng
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MJuanZeng)).Where("aid=? AND name LIKE ?", jsonData.Aid, "%"+jsonData.Name+"%")
	if jsonData.Id > 0 {
		tx = tx.Where("orderid=?", jsonData.Id)
	}
	if jsonData.Bid > 0 {
		tx = tx.Where("mid=?", jsonData.Bid)
	}
	if jsonData.Type >= 0 && jsonData.Type < 80 {
		tx = tx.Where("is_juan=?", jsonData.Type)
	}
	if jsonData.CreatedStart != "" {
		tx = tx.Where("created_at>?", define.TimeUnix(jsonData.CreatedStart))
	}
	if jsonData.CreatedEnd != "" {
		tx = tx.Where("created_at<?", define.TimeUnix(jsonData.CreatedEnd))
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 批量修改颁发证书
func JuanType(c *gin.Context) {
	var jsonData ProducStatusJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	tx := models.DB.Begin()
	//删除
	err = tx.Model(new(models.MJuanZeng)).Where("id IN ?", jsonData.ID).Update("is_juan", 1).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()
	str := define.ArrayToString(jsonData.ID)
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，批量颁发了证书id:" + str
	models.LogAdd(6, "颁发证书", userId, logData, bid, 1)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
